import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import viteCompression from 'vite-plugin-compression'
import legacyPlugin from '@vitejs/plugin-legacy'
import { createHtmlPlugin } from 'vite-plugin-html'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import'
import dynamicImport from 'vite-plugin-dynamic-import'
import { visualizer } from "rollup-plugin-visualizer";
import { mars3dPlugin } from 'vite-plugin-mars3d';
// // 当前执行node命令时文件夹的地址(工作目录)
const root = process.cwd()
export default defineConfig(({ mode }) => {
    let env = loadEnv(mode, process.cwd())
    return {
        base: env.VITE_BASE_PATH,
        root: root,
        server: {
            port: 8081,
            host: '0.0.0.0',
            open: false,
            proxy: {
                [env.VITE_API_BASEPATH]: {
                    target: env.VITE_API_URL,
                    rewrite: path => path.replace(RegExp(`^${env.VITE_API_BASEPATH}`), ''),
                    //开启代理
                    changeOrigin: true
                }
            }
        },
        plugins: [
            vue(),
			mars3dPlugin(),
            vueJsx(),
            vueDevTools(),
            dynamicImport(),
			visualizer({
				gzipSize: true,
				brotliSize: true,
				emitFile: false,
				filename: "test.html", //分析图生成的文件名
				open:true //如果存在本地服务端口，将在打包后自动展示
			}),
            legacyPlugin({
                targets: ['chrome 52'],
                additionalLegacyPolyfills: ['regenerator-runtime/runtime']
            }),
            viteCompression({
                verbose: true, // 是否在控制台输出压缩结果
                disable: false, // 是否禁用
                threshold: 10240, // 体积大于 threshold 才会被压缩,单位 b
                algorithm: 'gzip', // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
                ext: '.gz', // 生成的压缩包后缀
                deleteOriginFile: false //压缩后是否删除源文件
            }),
            //配置自动导入element start
            createStyleImportPlugin({
                resolves: [ElementPlusResolve()],
                libs: [
                    {
                        libraryName: 'element-plus',
                        esModule: true,
                        resolveStyle: name => {
                            return `element-plus/theme-chalk/${name}.css`
                        }
                    }
                ]
            }),
            AutoImport({
                resolvers: [ElementPlusResolver()]
            }),
            Components({
                resolvers: [ElementPlusResolver()]
            }),
            // 使用插件进行配置，固定写法，就这么写
            createHtmlPlugin({
                inject: {
                    data: {
                        // 这个就是要用到的参数
                        title: env.VITE_TITLE
                    }
                }
            })
        ],
        resolve: {
            extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.scss', '.css', '.vue'],
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
                '~@': fileURLToPath(new URL('./src', import.meta.url))
            }
        },
        // 公共css文件
        css: {
			extract: false,
            preprocessorOptions: {
                scss: {
					api: 'modern-compiler',
                    additionalData: `
						@use "@/assets/styles/index.scss" as *;
					`
                }
            }
        },
        // 打包配置
        build: {
            chunkSizeWarningLimit: 1000, // 提高超大静态资源警告大小
            minify: 'terser',
            // 输出路径
            outDir: env.VITE_OUT_DIR || 'dist',
            // 是否开启保留sourcemap文件
            sourcemap: env.VITE_SOURCEMAP === 'true' ? 'inline' : false,
            brotliSize: false,
            terserOptions: {
                // 是否清除 debugger 和 console
                compress: {
                    drop_debugger: env.VITE_DROP_DEBUGGER === 'true',
                    drop_console: env.VITE_DROP_CONSOLE === 'true'
                }
            },
            rollupOptions: {
				treeshake: true, // 开启 Tree Shaking，消除未使用的代码，减小最终的包大小
                output: {
                    chunkFileNames: 'static/js/[name]-[hash].js',
                    entryFileNames: 'static/js/[name]-[hash].js',
                    assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
							//使用pnpm打包
							return id.toString().split('node_modules/')[2].split('/')[0].toString()
                        }
                    }
                },
				commonjsOptions: {
					requireReturnsDefault: 'namespace', // 要求ES模块返回其名称空
				}
            }
        },
        // 暴露环境文件
        define: {
            'process.env': {}
        }
    }
})
